//
//  WQCMybankViewController.m
//  renxinghuan
//
//  Created by 王晓民 on 2018/4/11.
//  Copyright © 2018年 吴清翠. All rights reserved.
//

#import "WQCMybankViewController.h"
#import "configuration.h"
#import "WYCBankModel.h"
#import "WYCbankPickerView.h"
#import "WQCPlanDetailedViewController.h"
@interface WQCMybankViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView  *setTablleView;
@property(nonatomic,strong)NSArray  *titleSource;
@property(nonatomic,strong)UITextField *bankNumber;
@property(nonatomic,strong)UITextField *bankName;
@property(nonatomic,strong)UITextField *userName;
@property(nonatomic,strong)UITextField *userPhone;
@property(nonatomic,strong)UITextField *userBank;

@property(nonatomic,strong)WYCBankModel *bankModel;
@property(nonatomic,strong)NSMutableArray  *resultArray;
@property (nonatomic,weak)WYCbankPickerView  *bankPickerView;
@property(nonatomic,strong)UIButton  *bankkaihuhe;
@property(nonatomic,strong)NSString  *bankId;




@end

@implementation WQCMybankViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _resultArray = [[NSMutableArray alloc]init];
    [self loadPickBank];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *shoustr = [defaults objectForKey:@"firstName"];
    
    
    
    NSLog(@"数据 %@",shoustr);
    [self setupNav];
    [self setupTableView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
#pragma make -------->>TableView
- (void)setupTableView
{
    self.setTablleView = [[UITableView alloc] initWithFrame:CGRectMake(0, NavHeight, ScreenWidth,  ScreenHeight-200) style:UITableViewStyleGrouped];
    self.setTablleView.dataSource = self;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.setTablleView.delegate = self;
    self.setTablleView.scrollEnabled = NO;
    self.setTablleView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;//分割线
    
    [self.view addSubview:self.setTablleView];
    
    _titleSource = @[@"银行卡号",@"开户银行",@"持卡人",@"预留手机号"];
    UIButton * loginButton = [[UIButton alloc] init];
    loginButton.frame = CGRectMake(40 * px, ScreenHeight-150, ScreenWidth - 80 * px, 150 * px);
    loginButton.backgroundColor = wycMain;
    loginButton.layer.cornerRadius = 3;
    [loginButton setTitle:@"提交" forState:UIControlStateNormal];
    loginButton.titleLabel.font = [UIFont systemFontOfSize:72 * px];
    [loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginButton addTarget:self action:@selector(bindBankClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginButton];
}
- (void)setupNav
{
    self.navigationItem.title = @"绑定结算卡";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    [self.navigationController.navigationBar setBarTintColor:wycMain];
    
    self.view.backgroundColor = WYCGlobalBg;
}
-(void)bindBankClick
{
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]]; //字体颜色
    [SVProgressHUD setBackgroundColor:[UIColor blackColor]];   //背景颜色
    if(self.bankNumber.text.length == 0)
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"银行卡号不能为空"];
        return;
    }
    else if(_userBank.text.length == 0)
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"开户银行不能为空"];
        return;
    }
    else if(self.userName.text.length == 0)
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"持卡人不能为空"];
        return;
    }
    else if(self.userPhone.text.length == 0)
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"预留手机号不能为空"];
        return;
    }
    else
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *shoustr = [defaults objectForKey:@"firstName"];
      
        
      
        NSLog(@"数据 %@",shoustr);

        NSDictionary *json = @{@"cardNumber" : self.bankNumber.text,
                               @"bankName" : self.userBank.text,
                               @"bankId":self.bankId,
                               @"userId" :[WYCAccountTool unarchiveuserId],
                               @"name":self.userName.text,
                               @"sex":_sex,
                               @"nationality":_nationality,
                               @"birth":_birth,
                               @"address":_address,
                               @"issue":_issue,
                               @"startDate":_startDate,
                               @"endDate":_endDate,
                               @"faceUrl":_faceUrl,
                               @"backUrl":_backUrl,
                               @"holdIdCardUrl":shoustr,
                               @"mobile":self.userPhone.text,
                               @"num":_num,
                               };
    //把字符串转换为NSData
    NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
    //以NSData创建字符串对象
    
    NSString *dicStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    NSLog(@"字典转换为字符串是%@",dicStr);
    

    NSString *jsonRSA = [RSA encryptString:dicStr publicKey:RSA_P_KEY];

        NSMutableDictionary * params = [NSMutableDictionary dictionary];
        params[@"listParam"] =jsonRSA;
        NSLog(@"%@",params);
    
        [HttpTool POST:realAuth params:params success:^(NSURLSessionDataTask *task, id responseObject) {
    
            if ([[responseObject objectForKey:@"code"] intValue] == 0){
    
                [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"认证成功"];
                
                [self.navigationController popToRootViewControllerAnimated:YES];
                
                WYCAccount *account = [WYCAccountTool account];
                account.isAuth = @"0";
                account.userName = self.userName.text;
                [WYCAccountTool saveAccount:account];
                
                
                
    
            }else{
    
                [SVProgressHUD showImage:[UIImage imageNamed:@""] status:msgStr];
            }
        } fail:^(NSURLSessionDataTask *task, NSError *error) {
            [SVProgressHUD showImage:[UIImage imageNamed:@""] status:Failed];
        }];
    }
    
}
#pragma mark tableViewDelegate
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"结算卡必须为实名认证名下储蓄卡";
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //分组数 也就是section数
    return 1;
}

//设置每个分组下tableview的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

//设置每行对应的cell（展示的内容）
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifer=@"cell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifer];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
    }
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    cell.textLabel.text = [_titleSource objectAtIndex:indexPath.row];
    if (indexPath.row == 0) {
        UITextField  *bankNum = [[UITextField alloc]init];
        bankNum.frame = CGRectMake(110, 10, 250, 30);
        bankNum.placeholder = @"请输入银行卡号";
        bankNum.keyboardType = UIKeyboardTypeNumberPad;
        bankNum.textAlignment = NSTextAlignmentLeft;
        bankNum.font = [UIFont systemFontOfSize:14];
        [cell.contentView addSubview:bankNum];
        self.bankNumber =bankNum;
    }
    if (indexPath.row == 1) {
        UITextField  *bankNum = [[UITextField alloc]init];
        bankNum.frame = CGRectMake(110, 10, ScreenWidth-110, 30);
        bankNum.placeholder =@"请输入开户银行";
        bankNum.textAlignment = NSTextAlignmentLeft;
        bankNum.font = [UIFont systemFontOfSize:14];
        bankNum.enabled = NO;
        [cell.contentView addSubview:bankNum];
        self.userBank = bankNum;
        

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
    }
    else if (indexPath.row ==2)
    {
        UITextField  *bankNum = [[UITextField alloc]init];
        bankNum.frame = CGRectMake(110, 10, 250, 30);
        bankNum.text =self.name;
        bankNum.textAlignment = NSTextAlignmentLeft;
        bankNum.font = [UIFont systemFontOfSize:14];
        bankNum.enabled = NO;
        [cell.contentView addSubview:bankNum];
        self.userName = bankNum;
    }
    else if (indexPath.row ==3)
    {
        UITextField  *bankNum = [[UITextField alloc]init];
        bankNum.frame = CGRectMake(110, 10, 250, 30);
        bankNum.placeholder = @"请输入预留手机号";
        bankNum.textAlignment = NSTextAlignmentLeft;
        bankNum.keyboardType = UIKeyboardTypeNumberPad;

        bankNum.font = [UIFont systemFontOfSize:14];
        [cell.contentView addSubview:bankNum];
        self.userPhone = bankNum;
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==1) {
        [self pressPickbank];
    }
}
-(void)pressPickbank
{
    [self.bankPickerView removeFromSuperview];
    WYCbankPickerView *bankView = [[WYCbankPickerView alloc]initWithSourceData:self.resultArray confirmBlock:^(WYCBankModel *bankModel) {
        
        _bankModel = bankModel;
        _userBank.text =bankModel.bankName;
        self.bankId = bankModel.bankId;
        [self pickerViewhide:YES];
        
    } cancelBlock:^(WYCBankModel *bankModel) {
        [self pickerViewhide:YES];
        _userBank.text =bankModel.bankName;

        
    }];
    bankView.frame = CGRectMake(0, ScreenHeight-200, ScreenWidth, 200);
    self.bankPickerView = bankView;
    [self.view addSubview:self.bankPickerView];
    [self pickerViewhide:NO];
}

- (void)pickerViewhide:(BOOL)hide {
    
    if (hide) {
        
        [UIView animateWithDuration:1 animations:^{
            
            
            self.bankPickerView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, 280);
        }];
    }else {
        
        [UIView animateWithDuration:1 animations:^{
            
            self.bankPickerView.frame = CGRectMake(0, ScreenHeight - 200, ScreenWidth, 200);
        }];
    }
    
}
-(void)loadPickBank
{
    NSLog(@"选择信用卡");
    
    [HttpTool POST:banklist params:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@",responseObject);
        if ([[responseObject objectForKey:@"code"] intValue] == 0) {
            NSArray * resultArray = responseObject[@"result"];
            for (NSDictionary * dict in resultArray) {
                WYCBankModel * model = [WYCBankModel mj_objectWithKeyValues:dict];
                [self.resultArray addObject:model];
                self.bankModel = _bankModel;
                
            }
        }
        [self.bankPickerView refreshWithSourceData:self.resultArray];
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
    
}

@end
